﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using DataContext;
using EntityBLL;
using System.Globalization;
using System.Security.Cryptography;
using Utils;

namespace WorkFlowBLL
{
    public class CtrAdmin
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="adminID"></param>
        /// <param name="action">1: Thêm mới; 2: Sửa; 3: Xóa</param>
        /// <param name="description"></param>
        /// <returns></returns>
        public int LogInsert(int adminID, string uName, short action, string description, string functionName)
        {
            return DAL.AdminInstance.CreateInstance().uspLogInsert(adminID,uName, action, description,functionName, DateTime.Now);
        }
        public List<uspLogSearchResult> LogSearch(string userName,string functionName,short action,DateTime fromDate,DateTime toDate,int currentPage,int pageSize, ref int? totalRecord)
        {
            return DAL.AdminInstance.CreateInstance().uspLogSearch(userName, functionName, action, fromDate, toDate, currentPage, pageSize, ref totalRecord).ToList();
        }
        #region Admin
        /// <summary>
        /// Check đăng nhập User
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool CheckExistUser(string userName, string password)
        {
            int? ret = 0;
            DAL.AdminInstance.CreateInstance().uspAdminCheckLogin(userName, GetMD5UTF8(password), ref ret);
            if (ret != null) return (int)ret == 1;
            return false;
        }
        /// <summary>
        /// Check Login BackEnd
        /// </summary>
        /// <returns></returns>
        public bool CheckExistsAdminByUserName(string UserName)
        {
            int? ret = 0;
            DAL.AdminInstance.CreateInstance().uspAdminCheckExistsByUserName(UserName, ref ret);
            if (ret != null) return (int)ret == 1;
            return false;
        }

        /// <summary>
        /// Getinfo
        /// </summary>
        public uspAdminGetInfoByUserNameResult AdminGetInfoByUserName(string UserName)
        {
            return DAL.AdminInstance.CreateInstance().uspAdminGetInfoByUserName(UserName).ToList().FirstOrDefault();           
        }

        /// <summary>
        /// Kiểm tra admin đang đăng nhập có đươc quyền thực hiện chức năng truyền vào hay không?
        /// m_per:VTCO.Utils.AdminUtils.Permission
        /// </summary>
        public static int GetPermission(string m_permission,string funtion)
        {
            var mPermission = 0;
            if (!String.IsNullOrEmpty(m_permission) && !funtion.Equals(string.Empty))
            {
                var permissionList = m_permission.Split('|');
                string mPermission1 = (from permission in permissionList
                               select permission.Split('#')
                                   into arrTemp
                                   where arrTemp[0].ToLower().Equals(funtion.ToLower())
                                   select arrTemp[1]).FirstOrDefault();
                mPermission = Convert.ToInt32(mPermission1 == null ? "8" : mPermission1);
            }
            return mPermission;
        }       


        public uspAdminGetInfoByAdminIDResult GetInfoAdminByAdminID(int adminId)
        {
            return DAL.AdminInstance.CreateInstance().uspAdminGetInfoByAdminID(adminId).FirstOrDefault();
        }

        public uspAdminGetInfoByUserNameResult GetInfoAdminByUserName(string UserName)
        {
            return DAL.AdminInstance.CreateInstance().uspAdminGetInfoByUserName(UserName).ToList().FirstOrDefault();
        }

        public List<uspAdminGetListResult> GetListAdmin(string UserName, int adminID, int roleID, short status)
        {
            return DAL.AdminInstance.CreateInstance().uspAdminGetList(UserName, adminID, roleID, status).ToList();
        }

        public List<uspAdminGetListAllResult> GetListAdminAll()
        {
            return DAL.AdminInstance.CreateInstance().uspAdminGetListAll().ToList();
        }

        /// <summary>
        /// Mã hóa MD5
        /// </summary>
        /// <param name="_strValue"></param>
        /// <returns></returns>
        public static string GetMD5UTF8(string _strValue)
        {
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;
            md5 = new MD5CryptoServiceProvider();
            originalBytes = UTF8Encoding.Default.GetBytes(_strValue);
            encodedBytes = md5.ComputeHash(originalBytes);
            
            //Convert encoded bytes back to a 'readable' string
            return BitConverter.ToString(encodedBytes).ToLower().Replace("-", "");
        }

        public int InsertAdmin(string UserName, string fullName, DateTime birthday, string email, string phone, string description, short status, string pass)
        {
            pass = GetMD5UTF8(pass);
            if (birthday != null)
            {
                return DAL.AdminInstance.CreateInstance().uspAdminInsert(UserName, fullName, pass, birthday, email, phone, description, DateTime.Now, status);                
            }
            else
            {
                return DAL.AdminInstance.CreateInstance().uspAdminInsert(UserName, fullName,pass, null, email, phone, description, DateTime.Now, status);
            }

        }

        /// <summary>
        /// Cập nhật thông tin cá nhân Admin (do admin đó tự cập nhật thông tin cá nhân của mình)
        /// </summary>
        /// <param name="fullName"></param>
        /// <param name="birthday"></param>
        /// <param name="ym"> </param>
        /// <param name="phone"> </param>
        /// <returns></returns>
        public int UpdateAdminInfo(int adminID,string fullName, DateTime birthday, string ym, string phone, string des)
        {
            return DAL.AdminInstance.CreateInstance().uspAdminUpdateInfo(adminID, fullName, birthday, ym, phone,des);
        }

        public int UpdateAdminPass(int adminID, string pass)
        {
            pass = GetMD5UTF8(pass);
            return DAL.AdminInstance.CreateInstance().uspAdminUpdatePass(adminID, pass);
        }

        /// <summary>
        /// Admin cấp cao nhất cập nhật thông tin cua các user admin trong backend
        /// </summary>
        /// <param name="adminID"></param>
        /// <param name="status"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public int UpdateAdminStatus(int adminID, string description, short status)
        {
            return DAL.AdminInstance.CreateInstance().uspAdminUpdateStatus(adminID, description, status);
        }

        public int DeleteAdmin(int adminID)
        {
            return DAL.AdminInstance.CreateInstance().uspAdminDelete(adminID);
        }
        #endregion
        #region Role
        /// <summary>
        /// Thêm mới một Role
        /// </summary>
        /// <param name="name"></param>
        /// <param name="description"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public int InsertRole(string name, string description, short status)
        {         
            return DAL.AdminInstance.CreateInstance().uspRoleInsert(name, description, status);
        }

        /// <summary>
        /// Cập nhật thông tin chung của một Role
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="name"></param>
        /// <param name="description"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public int UpdateRole(int roleID, string name, string description, short status)
        {
            return DAL.AdminInstance.CreateInstance().uspRoleUpdateByRoleID(roleID, name, description, status);
        }

        /// <summary>
        /// Xóa một Role
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public int DeleteRole(int roleID)
        {
            return DAL.AdminInstance.CreateInstance().uspRoleDeleteByRoleID(roleID);
        }

        /// <summary>
        /// Lấy danh sách Role
        /// </summary>
        /// <returns></returns>
        public ClassExtend<int, uspRoleGetByStatusResult> GetListRole()
        {
            var objReturn = new ClassExtend<int, uspRoleGetByStatusResult>
            {
                Items =
                    DAL.AdminInstance.CreateInstance().uspRoleGetByStatus(-1).ToList()
            };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }

        /// <summary>
        /// Lấy thông tin chi tiết của một Role
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public uspRoleGetInfoByRoleIDResult GetRoleInfo(int roleID)
        {
            return DAL.AdminInstance.CreateInstance().uspRoleGetInfoByRoleID(roleID).ToList().FirstOrDefault();
        }

        /// <summary>
        /// Cập nhật Permission của một RoleFunction
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="functionID"></param>
        /// <param name="permission"> </param>
        /// <returns></returns>
        public int UpdateRoleFunction(int roleID, int functionID, int permission)
        {
            return DAL.AdminInstance.CreateInstance().uspRoleFunctionUpdate(roleID, functionID, permission);
        }
        #endregion
        #region function
        /// <summary>
        /// Thêm mới một Function
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parrentID"></param>
        /// <param name="url"> </param>
        /// <param name="status"></param>
        public int AddFunction(string name, int parrentID, string url, int status)
        {           
            return DAL.AdminInstance.CreateInstance().uspFunctionInsert(name, parrentID, url, status);
        }

        /// <summary>
        /// Cập nhật thông tin cho Function
        /// </summary>
        /// <param name="functionID"></param>
        /// <param name="name"></param>
        /// <param name="parrentID"></param>
        /// <param name="url"> </param>
        /// <param name="order"></param>
        /// <param name="status"></param>
        public int UpdateFunction(int functionID, string name, int parrentID, string url, int order, int status)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionUpdate(functionID, name, parrentID, url, order, status);
        }

        /// <summary>
        /// Xóa một Function
        /// </summary>
        /// <param name="functionID"></param>
        /// <returns></returns>
        public int DeleteFunction(int functionID)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionDelete(functionID);
        }

        /// <summary>
        /// Lấy danh sách Function theo danh mục cha
        /// </summary>
        /// <param name="parrentID"> </param>
        /// <param name="status">-1: Tất cả</param>
        /// <returns></returns>
        public ClassExtend<int, uspFunctionGetChildResult> GetChild(int parrentID, int status)
        {
            var objReturn = new ClassExtend<int, uspFunctionGetChildResult>
            {
                Items =
                    DAL.AdminInstance.CreateInstance().uspFunctionGetChild(parrentID, status).ToList()
            };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }

        /// <summary>
        /// Lấy thông tin chi tiết một Function
        /// </summary>
        /// <param name="functionID"></param>
        /// <returns></returns>
        public uspFunctionGetInfoResult GetInfoFunction(int functionID)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionGetInfo(functionID).FirstOrDefault();
        }

        /// <summary>
        /// Lấy danh sách Function theo cap
        /// </summary>
        /// <returns></returns>
        public ClassExtend<int, ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildResult>> GetListFunction()
        {
            var objReturn = new ClassExtend<int, ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildResult>>();

            var listFunction = GetChild(-1, -1);
            foreach (var item in listFunction.Items)
            {
                var listFuncChild = new ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildResult> { Info = item };
                var lstChild = GetChild(item.FunctionID, -1).Items;
                listFuncChild.Items = lstChild;
                listFuncChild.TotalRecord = lstChild.Count;
                objReturn.Items.Add(listFuncChild);
            }
            objReturn.TotalRecord = listFunction.TotalRecord;
            return objReturn;
        }

        public List<uspFunctionGetListByAdminIDResult> GetListFunctionByAdminID(int adminID, int parrentID)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionGetListByAdminID(adminID, parrentID).ToList();
        }

        public List<uspFunctionGetListByAdminRootResult> GetListFunctionByAdminRoot(int parrentID)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionGetListByAdminRoot(parrentID).ToList();
        }

        public List<uspFunctionGetListByAdminIDForLoginResult> GetListFunctionByAdminIDForLogin(int adminID)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionGetListByAdminIDForLogin(adminID).ToList();
        }

        public List<uspFunctionGetListByAdminRootForLoginResult> GetListFunctionByAdminRootForLogin()
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionGetListByAdminRootForLogin().ToList();
        }
        #endregion
        #region Permission
        /// <summary>
        /// Thêm mới một Permission
        /// </summary>
        /// <param name="adminID"></param>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public int InsertPermission(int adminID, int roleID)
        {
            return DAL.AdminInstance.CreateInstance().uspPermissionInsert(adminID, roleID);
        }

        /// <summary>
        /// Thêm mới nhiều admin vào một Role
        /// </summary>
        /// <param name="adminIDs"></param>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public int InsertPermissionMultiAdminToRole(string adminIDs, int roleID, ref string userNames)
        {
            return DAL.AdminInstance.CreateInstance().uspPermissionInsertMultiAdminToRole(roleID, adminIDs, ref userNames);
        }

        /// <summary>
        /// Xóa một Permission
        /// </summary>
        /// <param name="permissionID"></param>
        /// <returns></returns>
        public int DeletePermission(int permissionID, ref string UserName)
        {
            return DAL.AdminInstance.CreateInstance().uspPermissionDelete(permissionID, ref UserName);
        }

        /// <summary>
        /// Xóa nhiều Permission đồng thời
        /// </summary>
        /// <param name="permissionIDs"></param>
        /// <returns></returns>
        public int DeletePermissionMulti(string permissionIDs)
        {
            return DAL.AdminInstance.CreateInstance().uspPermissionDeleteMulti(permissionIDs);
        }

        /// <summary>
        /// Lấy danh sách Admin thuộc Role
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ClassExtend<int, uspPermissionGetListAdminInRoleResult> GetListAdminInRole(int roleID)
        {
            var objReturn = new ClassExtend<int, uspPermissionGetListAdminInRoleResult> { Items = DAL.AdminInstance.CreateInstance().uspPermissionGetListAdminInRole(roleID).ToList() };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }

        /// <summary>
        /// Lấy danh sách Admin không thuộc Role
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ClassExtend<int, uspPermissionGetListAdminNotInRoleResult> GetListAdminNotInRole(int roleID)
        {
            var objReturn = new ClassExtend<int, uspPermissionGetListAdminNotInRoleResult> { Items = DAL.AdminInstance.CreateInstance().uspPermissionGetListAdminNotInRole(roleID).ToList() };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }

        /// <summary>
        /// Lấy danh sách Role của của Admin
        /// </summary>
        /// <param name="adminID"></param>
        /// <returns></returns>
        public ClassExtend<int, uspPermissionGetListRoleInAdminResult> GetListRoleInAdmin(int adminID)
        {
            var objReturn = new ClassExtend<int, uspPermissionGetListRoleInAdminResult>
            {
                Items = DAL.AdminInstance.CreateInstance().uspPermissionGetListRoleInAdmin(adminID).ToList()
            };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }

        /// <summary>
        /// Lấy danh sách Role không thuộc Admin
        /// </summary>
        /// <param name="adminID"></param>
        /// <returns></returns>
        public ClassExtend<int, uspPermissionGetListRoleNotInAdminResult> GetListRoleNotInAdmin(int adminID)
        {
            var objReturn = new ClassExtend<int, uspPermissionGetListRoleNotInAdminResult>
            {
                Items = DAL.AdminInstance.CreateInstance().uspPermissionGetListRoleNotInAdmin(adminID).ToList()
            };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }
        #endregion
        #region RoleFunction
        /// <summary>
        /// Thêm mới một RoleFunction
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="functionID"> </param>
        /// <returns></returns>
        public int InsertRoleFunction(int roleID, int functionID)
        {            
            var functionInfo = GetInfoFunction(functionID);
            if (functionInfo.ParrentID == -1)
            {
                var functionIDs = "";
                foreach (var item in GetFunctionChildNotInRole(functionID, roleID))
                {
                    functionIDs += item.FunctionID.ToString(CultureInfo.InvariantCulture) + ',';
                }
                functionIDs = functionIDs.Substring(0, functionIDs.Length - 1);
                var ret = "";
                return DAL.AdminInstance.CreateInstance().uspRoleFunctionInsertMulti(roleID, functionIDs, ref ret);
            }
            return DAL.AdminInstance.CreateInstance().uspRoleFunctionInsert(roleID, functionID);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="functionsIDs"> </param>
        /// <returns></returns>
        public string InsertRoleFunctionMulti(int roleID, string functionsIDs)
        {
            var ret = "";
            var spFunctionIDs = functionsIDs.Split(',');
            foreach (var functionID in spFunctionIDs)
            {
                var result = InsertRoleFunction(roleID, Convert.ToInt32(functionID));
                ret += result.ToString(CultureInfo.InvariantCulture);
            }
            return ret;
        }

        /// <summary>
        /// Xá một RoleFunction
        /// </summary>
        /// <returns></returns>
        public int DeleteRoleFunction(int roleID, int menuID)
        {
            return DAL.AdminInstance.CreateInstance().uspRoleFunctionDelete(roleID, menuID);
        }

        /// <summary>
        /// Xóa đồng thời nhiều RoleFunction
        /// </summary>
        /// <returns></returns>
        public int DeleteRoleFunctionMulti(int roleID, string menuIDs)
        {
            return DAL.AdminInstance.CreateInstance().uspRoleFunctionDeleteMulti(roleID, menuIDs);
        }

        /// <summary>
        /// Lấy danh sách function con của một parrentFunction mà thuộc Role truyền vào
        /// </summary>
        /// <param name="parrentID"></param>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public List<uspFunctionGetChildInRoleResult> GetFunctionChildInRole(int parrentID, int roleID)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionGetChildInRole(parrentID, roleID).ToList();
        }

        /// <summary>
        /// Lấy danh sách function con của một parrentFunction mà không thuộc Role truyền vào
        /// </summary>
        /// <param name="parrentID"></param>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public List<uspFunctionGetChildNotInRoleResult> GetFunctionChildNotInRole(int parrentID, int roleID)
        {
            return DAL.AdminInstance.CreateInstance().uspFunctionGetChildNotInRole(parrentID, roleID).ToList();
        }

        /// <summary>
        /// Lấy danh sách Function không thuộc Role truyền vào
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ClassExtend<int, ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildNotInRoleResult>> GetFunctionNotInRole(int roleID)
        {
            var objReturn = new ClassExtend<int, ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildNotInRoleResult>>();            
            var listFunction = GetChild(-1, -1).Items;
            foreach (var item in listFunction)
            {
                var listFunctionChild = new ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildNotInRoleResult> { Info = item };
                var lstChild = GetFunctionChildNotInRole(item.FunctionID, roleID);
                listFunctionChild.Items = lstChild;
                listFunctionChild.TotalRecord = lstChild.Count;
                objReturn.Items.Add(listFunctionChild);
            }
            objReturn.TotalRecord = objReturn.Items.Count;
            return objReturn;
        }

        /// <summary>
        /// Lấy danh sách Function thuộc Role truyền vào
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public ClassExtend<int, ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildInRoleResult>> GetFunctionInRole(int roleID)
        {
            var objReturn = new ClassExtend<int, ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildInRoleResult>>();
            var listFunction = GetChild(-1, -1).Items;
            foreach (var item in listFunction)
            {
                var listFunctionChild = new ClassExtend<uspFunctionGetChildResult, uspFunctionGetChildInRoleResult> { Info = item };
                var lstChild = GetFunctionChildInRole(item.FunctionID, roleID);
                listFunctionChild.Items = lstChild;
                listFunctionChild.TotalRecord = lstChild.Count;
                objReturn.Items.Add(listFunctionChild);
            }
            objReturn.TotalRecord = objReturn.Items.Count;
            return objReturn;
        }

        /// <summary>
        /// Lấy danh sách Role theo FunctionID
        /// </summary>
        /// <returns></returns>
        public ClassExtend<int, uspRoleFunctionGetRoleInFunctionResult> GetListRoleInFunction(int functionID)
        {
            var objReturn = new ClassExtend<int, uspRoleFunctionGetRoleInFunctionResult> { Items = DAL.AdminInstance.CreateInstance().uspRoleFunctionGetRoleInFunction(functionID).ToList() };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }

        /// <summary>
        /// Lấy danh sách Role mà Funtion k có quyền
        /// </summary>
        /// <returns></returns>
        public ClassExtend<int, uspRoleFunctionGetRoleNotInFunctionResult> GetListRoleNotInFunction(int FunctionID)
        {
            var objReturn = new ClassExtend<int, uspRoleFunctionGetRoleNotInFunctionResult> { Items = DAL.AdminInstance.CreateInstance().uspRoleFunctionGetRoleNotInFunction(FunctionID).ToList() };
            objReturn.TotalRecord = objReturn.Items.Count;
            objReturn.Info = 0;
            return objReturn;
        }
        #endregion

        #region Cấu hình
        public int UpdateConfig(string name, string address, string phone, string notice)
        {
            return DAL.AdminInstance.CreateInstance().uspConfigUpdate(address, name, phone, notice);
        }
        public uspConfigGetInfoResult GetConfig()
        {
            return DAL.AdminInstance.CreateInstance().uspConfigGetInfo().FirstOrDefault();
        }
        public int UpdateCDKey(string cdKey)
        {
            return DAL.AdminInstance.CreateInstance().uspConfigUpdateCDKey(cdKey);
        }
        #endregion        
    }
}
